﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OnlineMovieTicket.Data.IRepository;
using System.Data.SqlClient;

namespace OnlineMovieTicket.Data.Repository
{
    public class MovieTimeTableRepository : IMovieTimeTableRepository
    {
        ONLINEMOVIETICKETEntities dataContent;

        public MovieTimeTableRepository()
        {
            dataContent = new ONLINEMOVIETICKETEntities();
        }

        public bool InsertMovieTimeTable(Model.MovieTimeTable movieTimeTable)
        {
            bool returnVal=false;
            try
            {
                dataContent.AddToMovieTimeTables(new MovieTimeTable { MovieCode = movieTimeTable.MovieCode, ScheduleID = movieTimeTable.ScheduleID, AssignDate = DateTime.Today, ShowingDate = movieTimeTable.ShowingDate });
                dataContent.SaveChanges();
                returnVal = true;
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return returnVal;
        }


        public bool DeleteMovieTimeTable(int movieAssignmentID)
        {
            bool returnVal = false;
            try
            {
                var data = dataContent.MovieTimeTables.FirstOrDefault(m => m.MovieAssignmentID == movieAssignmentID);
                if (data != null)
                {
                    dataContent.MovieTimeTables.DeleteObject(data);
                    dataContent.SaveChanges();
                    returnVal = true;
                }
                else
                    throw new Exception("Record not found");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return returnVal;
        }

        public IList<Model.MovieTimeTable> GetMovieTimeTable(int movieCode, int cinemaHallID, DateTime showingDate)
        {
            var data = (from d in dataContent.MovieTimeTables
                        join c in dataContent.CinemaTimeTables
                        on d.ScheduleID  equals c.ScheduleID
                         where d.MovieCode == movieCode
                         && c.CinemaHallID == cinemaHallID
                         && d.ShowingDate == showingDate                         
                        select new Model.MovieTimeTable
                        {
                           MovieAssignmentID = d.MovieAssignmentID,
                           ScheduleID = d.ScheduleID,
                           StartTime = c.StartTime,
                           ShowingDate = d.ShowingDate,
                           AssignDate = d.AssignDate
                        }).ToList();
            
            return data;
        }
    }

 
}
